﻿using RXY_Mall.AdminApi.Common;
using RXY_Mall.AdminApi.Models;
using RXY_Mall.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Data.Entity;
using RXY_Mall.Core;
using RXY_Mall.Domain;
using RXY_Mall.Core.Tool;

namespace RXY_Mall.AdminApi.Controllers
{
    /// <summary>
    /// 消息接口
    /// </summary>
    [RoutePrefix("Message")]
    [ApiSecurityFilter]
    public class MessageController : BaseApiController
    {
        private RXY_MallContext db = new RXY_MallContext();

        /// <summary>
        /// 订单通知-所有人或指定人
        /// </summary>
        [HttpGet]
        [Route("GetOrderMessages")]
        public async Task<Response<IPagedList<OrderMessage>>> GetOrderMessages(int user_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<OrderMessage>> result = new Response<IPagedList<OrderMessage>>();
            result.code = 0;
            try
            {
                result.code = 1;
                var source = db.gw_messages
                    .Include(m => m.gw_message_rule_order)
                    .Where(m => m.status == 1 && m.type == (int)MessageType.Order && (m.user_id == user_id || m.user_id == null))
                    .Select(m => new OrderMessage()
                    {
                        add_time = m.add_time,
                        content = m.content,
                        message_id = m.id,
                        message_type = (MessageType)m.type,
                        order_no = m.gw_message_rule_order.order_no,
                        order_status = (OrderStatus)m.gw_message_rule_order.order_status,
                        picture_url = m.picture_url,
                        summary = m.summary,
                        title = m.title,
                    });

                source = source.OrderByDescending(s => s.add_time);
                IPagedList<OrderMessage> pagelist = new PagedList<OrderMessage>(source, page_index, page_size);

                gw_message_check check = new gw_message_check()
                {
                    add_time = DateTime.Now,
                    message_type = (int)MessageType.Order,
                    user_id = user_id,
                };

                db.gw_message_checks.Add(check);

                await db.SaveChangesAsync();
                //pagelist.ToList().ForEach(p => p.date = TimeHelper.GetTimeStamp(p.add_time));
                foreach (var item in pagelist)
                {
                    item.date = TimeHelper.GetTimeStamp(item.add_time);
                    item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                }

                result.data = pagelist;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 红包通知-所有人或指定人
        /// </summary>
        [HttpGet]
        [Route("GetRedpacketMessages")]
        public async Task<Response<IPagedList<RedpacketMessage>>> GetRedpacketMessages(int user_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<RedpacketMessage>> result = new Response<IPagedList<RedpacketMessage>>();
            result.code = 0;
            try
            {
                result.code = 1;
                var source = db.gw_messages
                    .Include(m => m.gw_message_rule_redpacket)
                    //.Include(m => m.gw_message_rule_redpacket.gw_finance_redpacket.gw_finance_subsidy)
                    .Where(m => m.status == 1 && m.type == (int)MessageType.Redpacket && (m.user_id == user_id || m.user_id == null))
                    .Select(m => new RedpacketMessage()
                    {
                        add_time = m.add_time,
                        content = m.content,
                        message_id = m.id,
                        message_type = (MessageType)m.type,
                        redpacket_id = m.gw_message_rule_redpacket.redpacket_id,
                        redpacket_type = m.gw_message_rule_redpacket == null ? RedpacketType.拼手气鼓励金红包 : (RedpacketType)m.gw_message_rule_redpacket.redpacket_type,
                        picture_url = m.picture_url,
                        summary = m.summary,
                        title = m.title,
                        //total_cycle= (int?)m.gw_message_rule_redpacket.gw_finance_redpacket.gw_finance_subsidy.total_cycle
                    });
                source = source.OrderByDescending(s => s.add_time);
                IPagedList<RedpacketMessage> pagelist = new PagedList<RedpacketMessage>(source, page_index, page_size);
                //pagelist.ToList().ForEach(p => p.date = TimeHelper.GetTimeStamp(p.add_time));

                foreach (var item in pagelist)
                {
                    item.date = TimeHelper.GetTimeStamp(item.add_time);
                    item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                }

                gw_message_check check = new gw_message_check()
                {
                    add_time = DateTime.Now,
                    message_type = (int)MessageType.Redpacket,
                    user_id = user_id,
                };

                db.gw_message_checks.Add(check);

                await db.SaveChangesAsync();


                result.data = pagelist;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 优惠通知-所有人或指定人
        /// </summary>
        [HttpGet]
        [Route("GetDiscountMessages")]
        public async Task<Response<IPagedList<DiscountMessage>>> GetDiscountMessages(int user_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<DiscountMessage>> result = new Response<IPagedList<DiscountMessage>>();
            result.code = 0;
            try
            {
                result.code = 1;
                var source = db.gw_messages
                    .Include(m => m.gw_message_rule_discount)
                    .Include(m => m.gw_message_rule_discount.gw_marketing_coupon)
                    .Where(m => m.status == 1 && m.type == (int)MessageType.Discount && (m.user_id == user_id || m.user_id == null))
                    .Select(m => new DiscountMessage()
                    {
                        add_time = m.add_time,
                        content = m.content,
                        message_id = m.id,
                        message_type = (MessageType)m.type,
                        coupon_id = m.gw_message_rule_discount.coupon_id,
                        marketing_coupon = m.gw_message_rule_discount.gw_marketing_coupon,
                        discount_type = m.gw_message_rule_discount == null ? DiscountType.Coupon : (DiscountType)m.gw_message_rule_discount.discount_type,
                        picture_url = m.picture_url,
                        summary = m.summary,
                        title = m.title,
                    });
                source = source.OrderByDescending(s => s.add_time);
                IPagedList<DiscountMessage> pagelist = new PagedList<DiscountMessage>(source, page_index, page_size);

                if (pagelist != null && pagelist.Count > 0)
                {
                    foreach (var item in pagelist)
                    {
                        item.date = TimeHelper.GetTimeStamp(item.add_time);
                        item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                        if (item.marketing_coupon != null)
                        {
                            item.coupon = new GetCouponOutput()
                            {
                                coupon_id = item.marketing_coupon.id,
                                name = item.marketing_coupon.name,
                                //picture_url = item.marketing_coupon.picture_url,
                                amount = item.marketing_coupon.amount,
                                value = item.marketing_coupon.value,
                                type = item.marketing_coupon.type,
                                sort = item.marketing_coupon.sort,
                                remain_quantity = item.marketing_coupon.remain_quantity,
                                total_quantity = item.marketing_coupon.total_quantity,
                                is_all = item.marketing_coupon.is_all,
                                coupon_type = (CouponType)item.marketing_coupon.type,
                                end_date = TimeHelper.GetTimeStamp(item.marketing_coupon.end_date),
                                start_date = TimeHelper.GetTimeStamp(item.marketing_coupon.start_date),
                            };
                        }

                    }
                }

                gw_message_check check = new gw_message_check()
                {
                    add_time = DateTime.Now,
                    message_type = (int)MessageType.Discount,
                    user_id = user_id,
                };

                db.gw_message_checks.Add(check);

                await db.SaveChangesAsync();


                result.data = pagelist;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 钱包通知-所有人或指定人
        /// </summary>
        [HttpGet]
        [Route("GetWalletMessages")]
        public async Task<Response<IPagedList<WalletMessage>>> GetWalletMessages(int user_id, int page_index = 1, int page_size = 20)
        {
            Response<IPagedList<WalletMessage>> result = new Response<IPagedList<WalletMessage>>();
            result.code = 0;
            try
            {
                result.code = 1;
                var source = db.gw_messages
                    .Include(m => m.gw_message_rule_wallet)
                    .Where(m => m.status == 1 && m.type == (int)MessageType.Wallet && (m.user_id == user_id || m.user_id == null))
                    .Select(m => new WalletMessage()
                    {
                        add_time = m.add_time,
                        content = m.content,
                        message_id = m.id,
                        message_type = (MessageType)m.type,
                        wallet_type = m.gw_message_rule_wallet == null ? WalletType.Withdraw : (WalletType)m.gw_message_rule_wallet.wallet_type,
                        withdraw_id = m.gw_message_rule_wallet.withdraw_id,
                        picture_url = m.picture_url,
                        summary = m.summary,
                        title = m.title,
                    });
                source = source.OrderByDescending(s => s.add_time);
                IPagedList<WalletMessage> pagelist = new PagedList<WalletMessage>(source, page_index, page_size);

                foreach (var item in pagelist)
                {
                    item.date = TimeHelper.GetTimeStamp(item.add_time);
                    item.picture_url = HostHelper.GetImgUrl(item.picture_url);
                }
                gw_message_check check = new gw_message_check()
                {
                    add_time = DateTime.Now,
                    message_type = (int)MessageType.Discount,
                    user_id = user_id,
                };

                db.gw_message_checks.Add(check);

                await db.SaveChangesAsync();


                result.data = pagelist;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        /// <summary>
        /// 获得消息数量
        /// </summary>
        [HttpGet]
        [Route("GetMessageCount")]
        public async Task<Response<MessageCount>> GetMessageCount(int user_id)
        {
            Response<MessageCount> result = new Response<MessageCount>();
            result.code = 0;
            try
            {
                var checks = await db.gw_message_checks
                    .Where(c => c.user_id == user_id)
                    .GroupBy(c => c.message_type)
                    .Select(c => new
                    {
                        message_type = (MessageType)c.Key,
                        date = c.Max(item => item.add_time)
                    }).ToListAsync();
                var orderDate = DateTime.MinValue;
                var DiscountDate = DateTime.MinValue;
                var RedpacketDate = DateTime.MinValue;
                var WalletDate = DateTime.MinValue;
                foreach (var item in checks)
                {
                    switch (item.message_type)
                    {
                        case MessageType.Order:
                            orderDate = item.date;
                            break;
                        case MessageType.Discount:
                            DiscountDate = item.date;
                            break;
                        case MessageType.Redpacket:
                            RedpacketDate = item.date;
                            break;
                        case MessageType.Wallet:
                            WalletDate = item.date;
                            break;
                    }
                }

                var source = await db.gw_messages
                    .Where(m => m.status == 1 && (m.user_id == user_id || m.user_id == null)
                   && ((m.type == (int)MessageType.Order && m.add_time > orderDate)
                   || (m.type == (int)MessageType.Discount && m.add_time > DiscountDate)
                   || (m.type == (int)MessageType.Redpacket && m.add_time > RedpacketDate)
                   || (m.type == (int)MessageType.Wallet && m.add_time > WalletDate)))
                    .GroupBy(m => m.type)
                    .Select(m => new
                    {
                        message_type = (MessageType)m.Key,
                        count = m.Count()
                    })
                    .ToListAsync();

                var messageCount = new MessageCount()
                {
                    discount_count = 0,
                    order_count = 0,
                    redpacket_count = 0,
                    wallet_count = 0,
                };
                foreach (var item in source)
                {
                    switch (item.message_type)
                    {
                        case MessageType.Order:
                            messageCount.order_count = item.count;
                            break;
                        case MessageType.Discount:
                            messageCount.discount_count = item.count;
                            break;
                        case MessageType.Redpacket:
                            messageCount.redpacket_count = item.count;
                            break;
                        case MessageType.Wallet:
                            messageCount.wallet_count = item.count;
                            break;
                    }
                }

                result.data = messageCount;
                result.code = 1;
            }
            catch (Exception ex)
            {
                result.code = 2;
                result.msg = ex.Message;
                LogHelper.WriteLog(ex);
            }
            return result;
        }

        //TODO 系统通知

        //TODO 交易物流

    }
}
